
from datetime import datetime
import zmq
from zmq.utils import jsonapi
import Cookie

import django.core
from django.http import HttpRequest, HttpResponse, QueryDict
from django.core.handlers import base


class ZMQRequest(HttpRequest):
	"""docstring for ZMQRequest"""

	def __init__(self, environ, orig_req):
		super(ZMQRequest, self).__init__()

		self.orig_request_str = orig_req

		zpo = jsonapi.loads(orig_req)
		self.orig_request_obj = zpo

		self.host = environ['ZMQ_HOST']
		self.port = environ['ZMQ_PORT']
		self.transport = environ['ZMQ_TRANSPORT']

		environ['SERVER_PORT'] = self.port

		# Enforce structure, method selection and URI.
		# Make optional ???
		if not zpo.has_key('method'):
			raise InvalidZMQObject("No 'method' key in dmq request object")

		if zpo['method'] not in ('GET', 'POST', 'PUT', 'DELETE'):
			raise InvalidZMQObject("Invalid method, got %s, I only except one of: %s" % (
							zpo['method'], ('GET', 'POST', 'PUT', 'DELETE')))

		if not zpo.has_key('uri'):
			raise InvalidZMQObject("No 'uri' key in dmq request object")

		if zpo.has_key('domain'):
			environ['SERVER_NAME'] = zpo['domain'] 
		else:
			environ['SERVER_NAME'] = self.host

		script_name = base.get_script_name(environ)

		self.environ = environ
		self.path = zpo['uri']
		self.path_info = self.path
		if not self.path_info:
			self.path_info = u'/'

		self.META = environ
		self.META['PATH_INFO'] = self.path_info
		self.META['SCRIPT_NAME'] = script_name
		#self.method = environ['REQUEST_METHOD'].upper()
		self.method = zpo['method'].upper()

		self.zpo = zpo


		self.META = dict(environ.items())

		if zpo.has_key('params'):
			qdict = QueryDict('', mutable=True, encoding=None)
			qdict.update(zpo['params'])
			if self.method == 'GET' or self.method == 'DELETE':
				self.GET = qdict
			elif self.method == 'POST' or self.method == 'PUT':
				self.POST = qdict
			
	#__init__()
#ZMQRequest

class ZMQResponse(HttpResponse):
	"""docstring for ZMQResponse"""

	def __init__(self, request, resp_dict, status=None, content_type='application/json'):

		self.status_code = status or 200

		self.msg = {
				'success':True,
				'status':status,
				'payload':resp_dict,
				}

		if request.META.get('ZMQ_DEBUG', False):
			self.msg['orig_request_str'] = request.orig_request_str
			self.msg['orig_request_obj'] = request.orig_request_obj
			self.msg['time_stamp'] = datetime.now()

		super(ZMQResponse, self).__init__(
				content=self.msg, 
				mimetype='text/plain', 
				status=self.status_code,
				content_type=content_type)
	#__init__()

	def __str__(self):
		"""JSON encoding of response"""
		return jsonapi.dumps(self.msg, cls=django.core.serializers.json.DjangoJSONEncoder)
	#__str__()
	__repr__ = __str__

#ZMQResponse
